<?php

include('pagina.php');
include('database.php');
include('auth.php');
include('core.php');

// Verifica se esta autenticado com pelo menos nivel 3
validaPermissao(3);

// Verifica se houve envio de formulario
if (isset($_POST['submit']))
{
	switch ($_POST['references_to'])
	{
		case EMPLOYEE:
			$reference_id=$_POST['employee_id'];
			break;
		case LOCATION:
			$reference_id=$_POST['location_id'];
			break;
		case CUSTOMER:
			$reference_id=$_POST['customer_id'];
			break;
		case CONTACT:
			// cadastra contato
			query_bd("INSERT INTO contacts VALUES " .
			"(NULL, '{$_POST['expense_name']}', ". ($_POST['expense_number']? $_POST['expense_number'] : "NULL") . 
			", '{$_POST['expense_street']}', '{$_POST['expense_complement']}', " . 
			"'{$_POST['expense_city']}', '{$_POST['expense_state']}', '{$_POST['expense_zipcode']}', '{$_POST['expense_phone']}', " .
			"'{$_POST['expense_cellphone']}', '{$_POST['expense_email']}')");
			
			$reference_id = mysql_insert_id();
			break;
		default:
			$reference_id = 'NULL';
			break;
	}

	if ($_POST['is_period_duedate'] == 'TRUE')
	{
		// Verifica se a data eh valida
		if (strtotime($_POST['next_duedate']) < $_SERVER['REQUEST_TIME'])
		{
			header( "Location: expense_new.php?msg=Could not create period expense because the next due date is past." );
			exit;
		}
	
		// cria period duedate
		query_bd("INSERT INTO period_duedates VALUES " .
		"(NULL, '{$_POST['name']}', '{$_POST['description']}', {$_POST['category']}, '" . 
		date("Y-m-d", strtotime($_POST['next_duedate'])) . "', {$_POST['period']}, " .
		"-{$_POST['value']}, {$_POST['references_to']}, {$reference_id}, " . 
		($_POST['doc_number']? "'{$_POST['doc_number']}', " : "NULL, ") .
		($_POST['obs']? "'" . mysql_real_escape_string($_POST['obs']) . "')" : "NULL)"));
		
		$period_income_id = mysql_insert_id(); //pega ultimo id criado
		
		// cria due date do period due date
		query_bd("INSERT INTO duedates VALUES " .
		"(NULL, '{$_POST['name']}', '{$_POST['description']}', {$_POST['category']}, '" . 
		date("Y-m-d", strtotime($_POST['next_duedate'])) . 
		"' , -{$_POST['value']}, FALSE, {$_POST['references_to']}, {$reference_id}, " . 
		($_POST['doc_number']? "'{$_POST['doc_number']}', " : "NULL, ") .
		($_POST['obs']? "'" . mysql_real_escape_string($_POST['obs']) . "')" : "NULL)"));
		
		header( "Location: period_expense.php?id={$period_income_id}&msg=Period expense successfully created." );
		exit;
	}
	else
	{
		// cria due date
		query_bd("INSERT INTO duedates VALUES " .
		"(NULL, '{$_POST['name']}', '{$_POST['description']}', {$_POST['category']}, '" . 
		date("Y-m-d", strtotime($_POST['payday'])) . 
		"' , -{$_POST['value']}, FALSE, {$_POST['references_to']}, {$reference_id}, " . 
		($_POST['doc_number']? "'{$_POST['doc_number']}', " : "NULL, ") .
		($_POST['obs']? "'{$_POST['obs']}')" : "NULL)"));
		
		$income_id = mysql_insert_id();
		header( "Location: expense.php?id={$income_id}&msg=Expense successfully created." );
		exit;
	}
}

// Inicia cabecalho da pagina
pagina_inicio('ParkSys - New Expense');
adicionar_css('datechooser.css');
adicionar_js('datechooser.js');
adicionar_js('toggle.js');
adicionar_js('input-format.js');
pagina_head();

echo "<script type='text/javascript' language='JavaScript'>";

echo "function show_reference_div(divno)";
echo "{";
echo "	document.getElementById('references_to_". EMPLOYEE . "').style.display = 'none';";
echo "	document.getElementById('references_to_". LOCATION . "').style.display = 'none';";
echo "	document.getElementById('references_to_". CONTACT . "').style.display = 'none';";
echo "	document.getElementById('references_to_". CUSTOMER . "').style.display = 'none';";
echo "	document.getElementById('references_to_' + divno).style.display = '';";
echo "};";

?>

function checkForm()
{
	if (document.getElementById('expense_new').name.value.length == 0)
	{
		alert("The name field must not be empty.");
		return false;
	}
	else if (document.getElementById('expense_new').value.value == 0.0)
	{
		alert("The value field must be different from zero.");
		return false;
	}
	else
		return true;
};

<?php
echo "</script>";

// Pega o nome e id de todas as locacoes
$locations = array();
$resultado = query_bd("SELECT locations.id, contacts.name FROM locations, contacts " . 
	"WHERE locations.locationcontact=contacts.id AND locations.operating=TRUE " .
	"ORDER BY contacts.name");
while ($loc = mysql_fetch_array($resultado))
	$locations[] = $loc;

// Pega o nome e id de todas os funcionarios
$employees = array();
$resultado = query_bd("SELECT employees.id, contacts.name FROM employees, contacts WHERE employees.contact_id=contacts.id " .
	"ORDER BY contacts.name");
while ($empl = mysql_fetch_array($resultado))
	$employees[] = $empl;
	
// Pega o nome e id de todas os clientes
$customers = array();
$resultado = query_bd("SELECT customers.id, contacts.name FROM customers, contacts WHERE customers.contact_id=contacts.id " .
	"ORDER BY contacts.name");
while ($cust = mysql_fetch_array($resultado))
	$customers[] = $cust;

// Formulario de entrada
echo "<form id=expense_new class=big_form action=expense_new.php method=POST " . 
	"onSubmit='return checkForm()'>";

// Hidden information
echo "<input id=is_period_duedate type=HIDDEN name=is_period_duedate value=FALSE>";

echo "<h1>New Expense</h1><br>";
echo "<label for=name>Name:</label> <input type=TEXT id=name name=name value='" . @$_GET['name'] . "' size=40 maxlength=50><br>";
echo "<label for=description>Description:</label> <input type=TEXT id=description name=description value='" . @$_GET['description'] . 
     "' size=40 maxlength=100><br>";
echo "<label for=category>Category:</label> <select id=category name=category>";
foreach ($EXP_CATEGORIES as $num => $nome)
	echo "<option value={$num}" . ($_GET['category']==$num? " selected=SELECTED" : "") .">{$nome}</option>";
echo "</select><br>";
echo "<label for=value>Expense value:</label> $<input type=TEXT id=value name=value value='" . (isset($_GET['value'])? $_GET['value'] : "0.00") . 
	"' size=10 onChange='format_money(this)'><br>";
echo "<label for=references_to>Subjects to:</label> <select id=references_to name=references_to onChange='show_reference_div(this.value)'>";
foreach ($REFERENCES_TO as $num => $nome)
	if ($nome != 'Event' && $nome != 'Report')
		echo "<option value={$num}" . ($_GET['references_to']==$num? " selected=SELECTED" : "") .">{$nome}</option>";
echo "</select><br>";

echo "<div id=references_to_". OTHER . " style='display: none' ></div>";
echo "<div id=references_to_". EMPLOYEE . (@$_GET['references_to']==EMPLOYEE? ">" : " style='display: none'>");

echo "<label for=employee_id>Employee:</label> <select id=employee_id name='employee_id'>";
echo "<option value=0 >----employee----</option>";
foreach ($employees as $empl)
	echo	"<option value={$empl['id']}" . ($_GET['employee']==$empl['id']? " selected=SELECTED" : "") .">{$empl['name']}</option>";
unset($employees);	
echo "</select>";

echo "</div>";
echo "<div id=references_to_". CUSTOMER . (@$_GET['references_to']==CUSTOMER? ">" :" style='display: none'>");

echo "<label for=customer_id>Customer:</label> <select id=customer_id name='customer_id' >";
echo "<option value=0 >----customer----</option>";
foreach ($customers as $cust)
	echo	"<option value={$cust['id']}" . ($_GET['customer']==$cust['id']? " selected=SELECTED" : "") .">{$cust['name']}</option>";
unset($customers);	
echo "</select>";

echo "</div>";
echo "<div id=references_to_". LOCATION . (@$_GET['references_to']==LOCATION? ">" :" style='display: none'>");

echo "<label for=location_id>Location:</label> <select id=location_id name='location_id' >";
echo "<option value=0 >----location----</option>";
foreach ($locations as $loc)
	echo	"<option value={$loc['id']}" . ($_GET['location']==$loc['id']? " selected=SELECTED" : "") .">{$loc['name']}</option>";
unset($locations);	
echo "</select>";

echo "</div>";

echo "<div id=references_to_". CONTACT . (@$_GET['references_to']==CONTACT? ">" :" style='display: none'>");

echo "<hr><h2>Expense Contact</h2><br>";
echo "<label for=expense_name>Contact name:</label> <input type=TEXT id=expense_name name=expense_name value='' size=40 maxlength=80><br>";
echo "<label for=expense_number>Number:</label> <input type=TEXT id=expense_number name=expense_number value='' size=8 onChange='format_int(this)'>";
echo " <label for=expense_street>Street:</label> <input type=TEXT id=expense_street name=expense_street value='' size=30 maxlength=50>";
echo " <label for=expense_complement>Complement:</label> <input type=TEXT id=expense_complement name=expense_complement value='' size=10 maxlength=30><br>";
echo "<label for=expense_city>City:</label> <input type=TEXT id=expense_city name=expense_city value='' size=10 maxlength=30>";
echo " <label for=expense_state>State:</label> <input type=TEXT id=expense_state name=expense_state value='' size=8 maxlength=10>";
echo " <label for=expense_zipcode>Zipcode:</label> <input type=TEXT id=expense_zipcode name=expense_zipcode value='' size=6 maxlength=10><br>";
echo "<label for=expense_phone>Phone:</label> <input type=TEXT id=expense_phone name=expense_phone value='' size=12 maxlength=20>";
echo " <label for=expense_cellphone>Cellphone:</label> <input type=TEXT id=expense_cellphone name=expense_cellphone value='' size=12 maxlength=20><br>";
echo "<label for=expense_email>Email:</label> <input type=TEXT id=expense_email name=expense_email value='' size=20 maxlength=30>";

echo "</div>";

echo "<hr>";

echo "<div id=period_duedate style='display: none' >";
echo "<a href=\"javascript:toggle('period_duedate'); toggle('single_duedate');" . 
	"document.getElementById('is_period_duedate').setAttribute('value', 'FALSE')" .
	"\" title='Set this expense as a unique due date' >Single due date</a><br>";

echo "Period: <select name='period' >";
foreach ($DUEDATESPERIODS as $num => $nome)
		echo "<option value={$num}>{$nome}</option>";
echo "</select><br>";
echo "<label for=next_duedate>Next duedate:</label> <input id=next_duedate type=TEXT value='" . date("m/d/Y") . "' name='next_duedate' size=9>" . 
		"<img class=imgcalendar src='img/calendar.gif' onclick=\"showChooser(this, 'next_duedate', 'chooserSpan1', 2000, 2020, Date.patterns.ShortDatePattern, false);\" alt='calendar'>" .
		"<div id='chooserSpan1' class='dateChooser select-free' style='display: none; visibility: hidden; width: 160px;'></div>";
echo "</div>";

echo "<div id=single_duedate >";
echo "<a href=\"javascript:toggle('period_duedate'); toggle('single_duedate');" . 
	"document.getElementById('is_period_duedate').setAttribute('value', 'TRUE')" .
	"\" title='Set this expense to generate due dates periodically'>Period due dates</a><br>";

echo "<label for=payday>Duedate:</label> <input id=payday type=TEXT value='" . date("m/d/Y") . "' name='payday' size=9>" . 
		"<img class=imgcalendar src='img/calendar.gif' onclick=\"showChooser(this, 'payday', 'chooserSpan2', 2000, 2020, Date.patterns.ShortDatePattern, false);\" alt='calendar'>" .
		"<div id='chooserSpan2' class='dateChooser select-free' style='display: none; visibility: hidden; width: 160px;'></div>";
echo "</div>";

echo "<hr>";

echo "<label for=doc_number>Document number(if apply):</label> <input type=TEXT id=doc_number name=doc_number value='' size=15 maxlength=30><br>";
echo "<label for=obs>Observations:</label><br><textarea id=obs name=obs cols=40 rows=5>";
echo "</textarea>";
echo "<hr>";
echo "<input type=SUBMIT name=submit value='Submit'>";

echo "</form>";

// Finaliza pagina
pagina_fim();
?>
